package com.junxonline.instant.job.handler;

import cn.hutool.core.date.DateUtil;
import com.junxonline.instant.job.service.config.DataSourceService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 每月建表任务
 *
 * @author JunX
 * @date 2021-10-25
 */
@Log4j2
@Component
public class MonthCreateTableJob {

    @Autowired
    private DataSourceService dataSourceService;

    @XxlJob("monthCreateTableJob")
    public ReturnT<String> monthCreateTableJob() {
        log.info("-------开始执行[每月建表定时任务]-------");
        try {
            dataSourceService.createTable(getCreateTableSql());
            log.info("-------[每月建表定时任务]执行成功-------");
        } catch (Exception e) {
            log.error("-------[每月建表定时任务]执行出错-------");
            e.printStackTrace();
            return ReturnT.FAIL;
        }
        return ReturnT.SUCCESS;
    }

    private List<String> getCreateTableSql() {
        List<String> sqlList = new ArrayList<>();
        String pattern = "yyyyMM";
        // 获取现在的年月
        String currentDate = DateUtil.format(DateUtil.date(), pattern);
        // 创建当月的表
        sqlList.add("CREATE TABLE IF NOT EXISTS sys_log_operation_" + currentDate +  " LIKE sys_log_operation;");
        sqlList.add("CREATE TABLE IF NOT EXISTS sys_log_login_" + currentDate +  " LIKE sys_log_login;");
        sqlList.add("CREATE TABLE IF NOT EXISTS sys_log_api_" + currentDate +  " LIKE sys_log_api;");
        sqlList.add("CREATE TABLE IF NOT EXISTS th_log_operation_" + currentDate +  " LIKE th_log_operation;");
        sqlList.add("CREATE TABLE IF NOT EXISTS th_log_connect_" + currentDate +  " LIKE th_log_connect;");
        sqlList.add("CREATE TABLE IF NOT EXISTS th_log_push_" + currentDate +  " LIKE th_log_push;");
        // 获取下个月的年月
        String nextMonthDate = DateUtil.format(DateUtil.nextMonth(), pattern);
        // 创建下月的表
        sqlList.add("CREATE TABLE IF NOT EXISTS sys_log_operation_" + nextMonthDate +  " LIKE sys_log_operation;");
        sqlList.add("CREATE TABLE IF NOT EXISTS sys_log_login_" + nextMonthDate +  " LIKE sys_log_login;");
        sqlList.add("CREATE TABLE IF NOT EXISTS sys_log_api_" + nextMonthDate +  " LIKE sys_log_api;");
        sqlList.add("CREATE TABLE IF NOT EXISTS th_log_operation_" + nextMonthDate +  " LIKE th_log_operation;");
        sqlList.add("CREATE TABLE IF NOT EXISTS th_log_connect_" + nextMonthDate +  " LIKE th_log_connect;");
        sqlList.add("CREATE TABLE IF NOT EXISTS th_log_push_" + nextMonthDate +  " LIKE th_log_push;");
        return sqlList;
    }

}
